package org.sith.gl.taskmanager.server.servlets;

import org.sith.gl.taskmanager.server.db.dao.ApplicationContextKeeper;
import org.sith.gl.taskmanager.server.db.dao.UserEntity;
import org.sith.gl.taskmanager.server.db.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class AddUserServlet extends HttpServlet {
    private static final String[] DENIED_SYMBOLS = new String[]{" ", "@", "#", "!", "%", "^", "&", "*", "(", ")",
            "+", "=", "\\", "|", "]", "[", "}", "{", "?", ">", "<", ".", ",", ":", ";", "'", "\""};

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String login = request.getParameter("login");


        if (login == null || login.isEmpty()) {
            request.getSession().setAttribute("desc", "Empty login name");
            response.sendRedirect("addUser.jsp");
            return;
        }
        String deniedSymbol = haveDeniedSymbols(login);
        if (deniedSymbol != null) {
            request.getSession().setAttribute("desc", "Login have denied symbols: " + deniedSymbol);
            response.sendRedirect("addUser.jsp");
            return;
        }

        UserService userService = (UserService) ApplicationContextKeeper.getApplicationContext().getBean("userService");
        UserEntity userEntity = userService.findByLogin(login);
        if (userEntity == null) {
            userEntity = new UserEntity();
            userEntity.setLogin(login);
            userService.saveOrUpdate(userEntity);
            request.getSession().setAttribute("desc", "User was successful added");
            response.sendRedirect("addUser.jsp");
        } else {
            request.getSession().setAttribute("desc", "User with login " + login + " already exist");
            response.sendRedirect("addUser.jsp");
        }

    }

    private String haveDeniedSymbols(String login) {
        for (String deniedSymbol : DENIED_SYMBOLS) {
            boolean isExist = login.contains(deniedSymbol);
            if (isExist) {
                return deniedSymbol;
            }

        }
        return null;
    }

}
